package com.pipe.protocol.events;

import com.pipe.util.DateUtils;
import io.netty.buffer.ByteBuf;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

/**
 * @author Kiven
 */
public class BinLogEventHeader {
    private static Logger LOG = LoggerFactory.getLogger(BinLogEventHeader.class);

    private long timestamp;
    private byte eventType;
    private long serverId;
    private long eventSize;
    private long logPos;
    private short flags;

    public BinLogEventHeader() {
    }

    public BinLogEventHeader(long timestamp, byte eventType, long serverId, long eventSize, long logPos, short flags) {
        this.timestamp = timestamp;
        this.eventType = eventType;
        this.serverId = serverId;
        this.eventSize = eventSize;
        this.logPos = logPos;
        this.flags = flags;
    }

    public static BinLogEventHeader build(ByteBuf byteBuf) {
        long ts = (long)byteBuf.readUnsignedIntLE() * 1000;

        byte et = byteBuf.readByte();
        long si = byteBuf.readIntLE();
        long es = byteBuf.readIntLE();
        long lp = byteBuf.readIntLE();
        short f = byteBuf.readShortLE();
        return new BinLogEventHeader(ts, et, si, es, lp, f);
    }

    public boolean isQueryEvent() {
        return eventType == 0x02;
    }

    public boolean isUpdateRowsEventV2() {
        return eventType == 0x1f;
    }

    public boolean isWriteRowsEventV2() {
        return eventType == 0x1e;
    }

    public boolean isTableMapEvent() {
        return eventType == 0x13;
    }

    public boolean isRotateEvent() {
        return eventType == 0x04;
    }

    public boolean isFormatDescriptionEvent() {
        return eventType == 0x0f;
    }

    @Override
    public String toString() {
        return "BinLogEventHeader{" +
                "timestamp=" + DateUtils.timeStampToDate(timestamp) +
                ", eventType=" + Integer.toHexString(eventType & 0xFF) +
                ", serverId=" + serverId +
                ", eventSize=" + eventSize +
                ", logPos=" + logPos +
                ", flags=" + flags +
                '}';
    }
}